﻿using AutoMapper;
using IOA.MES.Business;
using IOA.MES.ClientApi.Models.Request.NQC;
using IOA.MES.ClientApi.Models.Response.NQC;
using IOA.MES.Common;
using IOA.MES.DataAccess.Enum;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;

namespace IOA.MES.ClientApi.Controllers
{
    /// <summary>
    /// NQ数据拉取
    /// </summary>
    public class NQCController : ApiController
    {
        /// <summary>
        /// 查询等级列表
        /// </summary>
        [HttpPost]
        public ResultJson<QueryLevelsResponse> QueryLevels([FromBody] QueryLevelsRequest request)
        {
            var levels = new LevelColorMgr().QueryLevels();

            return new ResultJson<QueryLevelsResponse>(new QueryLevelsResponse { Levels = levels.Select(_ => _.Level).ToList() });
        }

        /// <summary>
        /// 查询异常原因
        /// </summary>
        [HttpPost]
        public ResultJson<QueryBadReasonsResponse> QueryBadReasons([FromBody] QueryBadReasonsRequest request)
        {
            var reasons = new BadReasonMgr().QueryReasons(request.ReasonType);
            return new ResultJson<QueryBadReasonsResponse>(new QueryBadReasonsResponse
            {
                BadReasons = reasons.Select(_ => new BadReason
                {
                    ReasonCode = _.ReasonCode,
                    KeyIndex = _.KeyIndex,
                    ReasonCN = _.ReasonCN
                }).ToList()
            });
        }

        /// <summary>
        /// 查询叠返异常原因
        /// </summary>
        [HttpPost]
        public ResultJson<QueryBadReasonsResponse> QueryDFBadReasons([FromBody] QueryBadReasonsRequest request)
        {
            var reasons = new BadReasonMgr().QueryReasons(request.ReasonType);
            return new ResultJson<QueryBadReasonsResponse>(new QueryBadReasonsResponse
            {
                BadReasons = reasons.Select(_ => new BadReason
                {
                    ReasonCode = _.ReasonCode,
                    KeyIndex = _.KeyIndex,
                    ReasonCN = _.ReasonCN
                }).ToList()
            });
        }

        ///<summary>
        ///叠层返修获取前EL不良
        /// </summary>
        [HttpPost]
        public ResultJson<GetLaminatorReworkResponse> GetLaminatorReworktData([FromBody] GetLaminatorReworkRequest request)
        {
            request.BarCode = request.BarCode.Replace("\r", "").Replace("\\r", "").ToUpper().Trim();
            var productviarecord = new ProductViaSiteMgr().GetProductViaSiteRecord(request.BarCode, "Q1", SiteType.EL1);
            if (productviarecord == null)
            {
                throw new MultiLanBizException(110001, request.BarCode);// "此组件无前EL过站记录");
            }

            return new ResultJson<GetLaminatorReworkResponse>(new GetLaminatorReworkResponse
            {
                BarCode = productviarecord.Code,
                ReasonCN = productviarecord.BadReason,
                CreateTime = productviarecord.CreateTime,
                ModifyTime = productviarecord.ModifyTime.ToString()
            }); ;
        }

        /// <summary>
        /// 获取终检/IV/铭牌数据
        /// </summary>
        [HttpPost]
        public ResultJson<GetFinalInspectDataResponse> GetFinalInspectData([FromBody] GetFinalInspectDataRequest request)
        {
            request.BarCode = request.BarCode.Replace("\r", "").Replace("\\r", "").ToUpper().Trim();
            var component = new ComponentMgr().GetComponent(request.BarCode);
            if (component == null)
            {
                throw new MultiLanBizException(110001, request.BarCode);// "组件条码不存在");
            }
            var ivData = new ProductViaSiteMgr().GetIvData(request.BarCode);
            //终检按11按钮跳过IV数据判断
            //if (ivData == null)
            //{
            //    throw new MultiLanBizException(110099, request.BarCode);// "IV数据不存在，请重新过IV");
            //}
            var el2Image = new ProductViaSiteMgr().GetImages(request.BarCode, SiteType.EL2).FirstOrDefault() ?? string.Empty;
            //if (string.IsNullOrWhiteSpace(el2Image))
            //{
            //    throw new MultiLanBizException(110098, request.BarCode);// "EL2图片不存在，请重新过EL2");
            //}
            return new ResultJson<GetFinalInspectDataResponse>(new GetFinalInspectDataResponse
            {
                WokrOrderNo = component.WorkOrderNo,
                ComponentColorCode = component.ComponentColor,
                ComponentColor = component.ComponentColor,
                SchemaName = ivData?.SchemaName ?? string.Empty,
                NameplateModel = component.NameplateModel,
                QLevel = component.QLevel,
                El2Image = el2Image,
                IvData = Mapper.Map<IvData>(ivData),
                Downgrade = string.IsNullOrWhiteSpace(component.QLevel) || string.Equals(component.QLevel, "Q1", System.StringComparison.CurrentCultureIgnoreCase) ? string.Empty
                    : $"等级：{component.QLevel}，异常：{component.DowngradeCode}-{component.DowngradeName}",
                NameplatData = new List<KeyValuePair<string, string>>
                {
                    new KeyValuePair<string, string>("条码", request.BarCode),
                    new KeyValuePair<string, string>("额定功率", component.IVPowerLevel.HasValue ? component.IVPowerLevel.Value.ToString("0") : ""),
                    new KeyValuePair<string, string>("铭牌型号", component?.NameplateModel),
                    new KeyValuePair<string, string>("等级", component.QLevel),
                    new KeyValuePair<string, string>("档位", component.IVCurrentLevel),
                    new KeyValuePair<string, string>("颜色", component.ComponentColor),
                    new KeyValuePair<string, string>("bpmax", !(ivData?.Pmax).HasValue ? string.Empty : ivData.Pmax.Value.ToString("0") + "w"),
                    new KeyValuePair<string, string>("bimp", !(ivData?.Im).HasValue ? string.Empty : ivData.Im.Value.ToString("0.00") + "A"),
                    new KeyValuePair<string, string>("bvmp", !(ivData?.Vm).HasValue ? string.Empty : ivData.Vm.Value.ToString("0.0") + "V"),
                    new KeyValuePair<string, string>("bisc", !(ivData?.Isc).HasValue ? string.Empty : ivData.Isc.Value.ToString("0.00") + "A"),
                    new KeyValuePair<string, string>("bvoc", !(ivData?.Voc).HasValue ? string.Empty : ivData.Voc.Value.ToString("0.0") + "V"),
                    new KeyValuePair<string, string>("spmax", !(ivData?.Pmax).HasValue ? string.Empty : ivData.Pmax.Value.ToString("0 W")),
                    new KeyValuePair<string, string>("simp", !(ivData?.Im).HasValue ? string.Empty : ivData.Im.Value.ToString("0.00000000")),
                    new KeyValuePair<string, string>("svmp", !(ivData?.Vm).HasValue ? string.Empty : ivData.Vm.Value.ToString("0.00000000")),
                    new KeyValuePair<string, string>("sisc", !(ivData?.Isc).HasValue ? string.Empty : ivData.Isc.Value.ToString("0.00000000")),
                    new KeyValuePair<string, string>("svoc", !(ivData?.Voc).HasValue ? string.Empty : ivData.Voc.Value.ToString("0.00000000")),
                    new KeyValuePair<string, string>("sff", !(ivData?.FF).HasValue ? string.Empty : ivData.FF.Value.ToString("0.0000")),
                    new KeyValuePair<string, string>("stemp", !(ivData?.Temp).HasValue ? string.Empty : ivData.Temp.Value.ToString("0.00")),
                    new KeyValuePair<string, string>("时间", ivData == null ? string.Empty : ivData.CreateTime.ToString("yyyy年MM月dd日HH时mm分ss秒")),
                    new KeyValuePair<string, string>("mvolt", ""),
                    new KeyValuePair<string, string>("mfuse", ""),
                    new KeyValuePair<string, string>("iecvolt", ""),
                    new KeyValuePair<string, string>("iecfuse", ""),
                    new KeyValuePair<string, string>("Pre_fix", ""),
                    new KeyValuePair<string, string>("CountryOrigin", ""),
                    new KeyValuePair<string, string>("ArtNo", ""),
                    new KeyValuePair<string, string>("in_code", ""),
                    new KeyValuePair<string, string>("电池来源", ""),
                    new KeyValuePair<string, string>("背板", ""),
                    new KeyValuePair<string, string>("认证码", ""),
                    new KeyValuePair<string, string>("模型代码", ""),
                    new KeyValuePair<string, string>("认证日期", ""),
                    new KeyValuePair<string, string>("备注", ""),
                    new KeyValuePair<string, string>("协鑫二维码", "")
                }
            });
        }

        /// <summary>
        /// 获取终检选项
        /// </summary>
        [HttpPost]
        public ResultJson<GetFinalInspectSelectionsResponse> GetFinalInspectSelections([FromBody] GetFinalInspectSelectionsRequest request)
        {
            var levels = new LevelColorMgr().QueryLevels();
            var reasons = new BadReasonMgr().QueryReasons(JudgeType.FinalInspection);

            return new ResultJson<GetFinalInspectSelectionsResponse>(new GetFinalInspectSelectionsResponse
            {
                QLevels = levels.OrderBy(_ => _.SortNo).Select(_ => _.Level).ToList(),
                BadReasons = reasons.Select(_ => $"{_.ReasonCode}-{_.ReasonCN}" + (string.IsNullOrWhiteSpace(_.ReasonVN) ? string.Empty : $"({_.ReasonVN})")).ToList(),
                CellFeatures = new List<string> { "圆倒角", "直倒角" },
                ComponentTypes = new List<string> { "一般", "黑色" }
            });
        }
    }
}
